package com.xishu.controller;

import com.xishu.entity.customer.*;
import com.xishu.entity.shop.DiscountTicket;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.CompanyService;
import com.xishu.service.CustomerService;
import com.xishu.service.DiscountTicketService;
import com.xishu.util.DateUtil;
import com.xishu.util.Tools;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
public class VipTicketConfigController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(VipTicketConfigController.class);
    private CustomerService customerService = CustomerService.getInstance();
    private CompanyService companyService = CompanyService.getInstance();
    private CommonService commonService = CommonService.getInstance();

    @ApiOperation(value = "创建会员等级的优惠卷")
    @PostMapping(value = ("/vip/level/ticket/config"), produces = ("application/json;charset=UTF-8"))
    public ResponseData create(@RequestBody VipLevelTicketConfig vipLevelTicketConfig) throws Exception {
        Long levelId = vipLevelTicketConfig.getLevelId();
        Long ticketId = vipLevelTicketConfig.getTicketId();
        boolean own = companyService.ownVipLevel(levelId);
        VerifyUtil.verify(() -> own);

        Optional<DiscountTicket> discountTicketOptional = DiscountTicketService.getInstance().findTicketOptional(ticketId);
        VerifyUtil.verify(() -> discountTicketOptional.isPresent());
        DiscountTicket discountTicket = discountTicketOptional.get();
        //必要要是线上的优惠卷才行
        VerifyUtil.verify(() -> getBoolean(discountTicket.getOnlineTicket()));

        VipLevel vipLevel = commonService.findEntity(levelId, VipLevel.class);
        vipLevelTicketConfig.setCompanyId(vipLevel.getCompanyId());

        if (getBoolean(vipLevel.getVip())) {
            vipLevelTicketConfig.setVip(true);
        }

        addThisTicketToCustomer(vipLevelTicketConfig);

        return commonService.createObject(vipLevelTicketConfig);
    }

    //给该会员等级的会员派卷
    private void addThisTicketToCustomer(VipLevelTicketConfig vipLevelTicketConfig) {
        Long levelId = vipLevelTicketConfig.getLevelId();
        Long ticketId = vipLevelTicketConfig.getTicketId();

        Long companyId = vipLevelTicketConfig.getCompanyId();

        Customer customer = new Customer();
        customer.setCompanyId(companyId);
        customer.setVipLevelId(levelId);

        try {
            commonService.doAll(customer, c -> {
                try {
                    //会员状态不正常，不用送
                    if (getInt(c.getStatus()) != 0) {
                        logger.info("customer {} status {}", c.getId(), c.getStatus());
                        return;
                    }

                    //派送几张
                    int ticketNumber = 1;
                    if (getInt(vipLevelTicketConfig.getTicketNumber()) >= 1) {
                        ticketNumber = vipLevelTicketConfig.getTicketNumber();
                    }
                    for (int i = 0; i < ticketNumber; i++) {
                        DiscountTicketService discountTicketService = DiscountTicketService.getInstance();
                        Optional<DiscountTicket> discountTicketOptional = discountTicketService.findTicketOptional(ticketId);
                        if (discountTicketOptional.isPresent()) {
                            DiscountTicket discountTicket = discountTicketOptional.get();
                            DiscountTicket realTicket = discountTicketService.createRealTicket(discountTicket);
                            customerService.addTicketToCustomer(realTicket, c.getId(), null, vipLevelTicketConfig.getLimitNumber(), vipLevelTicketConfig);
                        }
                    }
                } catch (Exception e) {
                    logger.error("e", e);
                }

            });

        } catch (Exception e) {
            logger.error("e", e);
        }


    }

    @ApiOperation(value = "修改会员等级的优惠卷")
    @PutMapping(value = ("/vip/level/ticket/config/modify"), produces = ("application/json;charset=UTF-8"))
    public ResponseData modify(@RequestBody VipLevelTicketConfig vipLevelTicketConfig) throws Exception {
        Long id = vipLevelTicketConfig.getId();
        VipLevelTicketConfig vipLevelTicketConfigInDb = commonService.findEntity(id, VipLevelTicketConfig.class);
        boolean own = companyService.ownVipLevel(vipLevelTicketConfigInDb.getLevelId());
        VerifyUtil.verify(() -> own);

        return commonService.updateObject(vipLevelTicketConfig, (ticketConfig) -> {
            PeriodTimeConfig periodTimeConfig = ticketConfig.getPeriodTimeConfig();

            //一次性券
            if (periodTimeConfig != null && getBoolean(periodTimeConfig.getOnce())) {
            }
        });
    }

    @ApiOperation(value = "查询会员等级的优惠卷")
    @PutMapping(value = ("/vip/level/ticket/config"), produces = ("application/json;charset=UTF-8"))
    public ResponseData search(@RequestBody VipLevelTicketConfig vipLevelTicketConfig) throws Exception {
        return commonService.searchResponse(vipLevelTicketConfig, (v) -> {
            try {
                Long ticketId = v.getTicketId();
                Optional<DiscountTicket> discountTicketOptional = DiscountTicketService.getInstance().findTicketOptional(ticketId);
                if (discountTicketOptional.isPresent()) {
                    DiscountTicket discountTicket = discountTicketOptional.get();
                    v.setTicketName(discountTicket.getName());
                    v.setTicketName_zh(discountTicket.getName_zh());
                    v.setTicketName_en(discountTicket.getName_en());
                } else {
                    //优惠券已经被删除了
                    commonService.delete(v);
                }
            } catch (Exception e) {
                logger.error("e", e);
            }
        }, (list) -> {
            return list.stream().filter(p -> isNotEmpty(p.getTicketName())).collect(Collectors.toList());
        });
    }

    @ApiOperation(value = "删除会员等级的优惠卷")
    @DeleteMapping(value = ("/vip/level/ticket/config"), produces = ("application/json;charset=UTF-8"))
    public ResponseData delete(@RequestBody VipLevelTicketConfig vipLevelTicketConfig) throws Exception {
        Long id = vipLevelTicketConfig.getId();
        VipLevelTicketConfig vipLevelTicketConfigInDb = commonService.findEntity(id, VipLevelTicketConfig.class);
        boolean own = companyService.ownVipLevel(vipLevelTicketConfigInDb.getLevelId());
        VerifyUtil.verify(() -> own);

        return commonService.delete(vipLevelTicketConfig);
    }

}
